import java.io.Serializable;
import java.lang.reflect.Field;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

// BaseEntity.java - 使用泛型
abstract class BaseEntity<T> implements Serializable {
    protected Integer id;

    public abstract T getId();
    public abstract void setId(T id);
}

// Employee.java - 使用序列化
class Employee extends BaseEntity<Integer> implements Serializable {
    private Integer id;
    private String name;
    private String gender;
    private Date birthday;
    private String position;
    private String phone;

    public Employee() {}

    public Employee(String name, String gender, Date birthday, String position, String phone) {
        this.name = name;
        this.gender = gender;
        this.birthday = birthday;
        this.position = position;
        this.phone = phone;
    }

    @Override
    public Integer getId() { return id; }
    @Override
    public void setId(Integer id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public String getGender() { return gender; }
    public void setGender(String gender) { this.gender = gender; }

    public Date getBirthday() { return birthday; }
    public void setBirthday(Date birthday) { this.birthday = birthday; }

    public String getPosition() { return position; }
    public void setPosition(String position) { this.position = position; }

    public String getPhone() { return phone; }
    public void setPhone(String phone) { this.phone = phone; }
}

// Crop.java
class Crop extends BaseEntity<Integer> implements Serializable {
    private String name;
    private String type;
    private Integer growthCycle;
    private Double price;

    public Crop() {}

    public Crop(String name, String type, Integer growthCycle, Double price) {
        this.name = name;
        this.type = type;
        this.growthCycle = growthCycle;
        this.price = price;
    }

    @Override
    public Integer getId() { return id; }
    @Override
    public void setId(Integer id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public String getType() { return type; }
    public void setType(String type) { this.type = type; }

    public Integer getGrowthCycle() { return growthCycle; }
    public void setGrowthCycle(Integer growthCycle) { this.growthCycle = growthCycle; }

    public Double getPrice() { return price; }
    public void setPrice(Double price) { this.price = price; }
}

// Land.java
class Land extends BaseEntity<Integer> implements Serializable {
    private Double area;
    private String soilType;
    private String status;

    public Land() {}

    public Land(Double area, String soilType, String status) {
        this.area = area;
        this.soilType = soilType;
        this.status = status;
    }

    @Override
    public Integer getId() { return id; }
    @Override
    public void setId(Integer id) { this.id = id; }

    public Double getArea() { return area; }
    public void setArea(Double area) { this.area = area; }

    public String getSoilType() { return soilType; }
    public void setSoilType(String soilType) { this.soilType = soilType; }

    public String getStatus() { return status; }
    public void setStatus(String status) { this.status = status; }
}

// PlantingPlan.java
class PlantingPlan extends BaseEntity<Integer> implements Serializable {
    private Integer cropId;
    private Integer landId;
    private Integer employeeId;
    private Date planDate;
    private Date estimatedHarvestDate;
    private Date actualHarvestDate;
    private String status;

    public PlantingPlan() {}

    public PlantingPlan(Integer cropId, Integer landId, Integer employeeId, Date planDate,
                        Date estimatedHarvestDate, Date actualHarvestDate, String status) {
        this.cropId = cropId;
        this.landId = landId;
        this.employeeId = employeeId;
        this.planDate = planDate;
        this.estimatedHarvestDate = estimatedHarvestDate;
        this.actualHarvestDate = actualHarvestDate;
        this.status = status;
    }

    @Override
    public Integer getId() { return id; }
    @Override
    public void setId(Integer id) { this.id = id; }

    public Integer getCropId() { return cropId; }
    public void setCropId(Integer cropId) { this.cropId = cropId; }

    public Integer getLandId() { return landId; }
    public void setLandId(Integer landId) { this.landId = landId; }

    public Integer getEmployeeId() { return employeeId; }
    public void setEmployeeId(Integer employeeId) { this.employeeId = employeeId; }

    public Date getPlanDate() { return planDate; }
    public void setPlanDate(Date planDate) { this.planDate = planDate; }

    public Date getEstimatedHarvestDate() { return estimatedHarvestDate; }
    public void setEstimatedHarvestDate(Date estimatedHarvestDate) { this.estimatedHarvestDate = estimatedHarvestDate; }

    public Date getActualHarvestDate() { return actualHarvestDate; }
    public void setActualHarvestDate(Date actualHarvestDate) { this.actualHarvestDate = actualHarvestDate; }

    public String getStatus() { return status; }
    public void setStatus(String status) { this.status = status; }
}

// DBUtil.java - 使用反射和泛型
class DBUtil {
    private static final String URL = "jdbc:mysql://localhost:3306/farm_management";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 使用反射将ResultSet转换为实体对象
    public static <T> T resultSetToEntity(ResultSet rs, Class<T> clazz) {
        try {
            T entity = clazz.newInstance();
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();

            for (int i = 1; i <= columnCount; i++) {
                String columnName = metaData.getColumnName(i);
                Object value = rs.getObject(i);

                // 使用反射设置属性值
                Field field = clazz.getDeclaredField(convertColumnNameToFieldName(columnName));
                field.setAccessible(true);
                field.set(entity, value);
            }

            return entity;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String convertColumnNameToFieldName(String columnName) {
        // 将数据库列名转换为Java字段名（下划线转驼峰）
        StringBuilder fieldName = new StringBuilder();
        boolean nextUpper = false;

        for (int i = 0; i < columnName.length(); i++) {
            char c = columnName.charAt(i);

            if (c == '_') {
                nextUpper = true;
            } else {
                if (nextUpper) {
                    fieldName.append(Character.toUpperCase(c));
                    nextUpper = false;
                } else {
                    fieldName.append(Character.toLowerCase(c));
                }
            }
        }

        return fieldName.toString();
    }
}

// BaseDAO.java - 使用泛型
interface BaseDAO<T> {
    List<T> findAll(); // 使用集合
    T findById(Integer id);
    boolean save(T entity);
    boolean update(T entity);
    boolean delete(Integer id);
}

// EmployeeDAOImpl.java - 使用集合和泛型
class EmployeeDAOImpl implements BaseDAO<Employee> {
    @Override
    public List<Employee> findAll() {
        List<Employee> employees = new ArrayList<>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM employee";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();

            while (rs.next()) {
                Employee employee = DBUtil.resultSetToEntity(rs, Employee.class);
                employees.add(employee);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, rs);
        }

        return employees;
    }

    @Override
    public Employee findById(Integer id) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM employee WHERE id = ?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, id);
            rs = ps.executeQuery();

            if (rs.next()) {
                return DBUtil.resultSetToEntity(rs, Employee.class);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, rs);
        }

        return null;
    }

    @Override
    public boolean save(Employee employee) {
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO employee(name, gender, birthday, position, phone) VALUES (?, ?, ?, ?, ?)";
            ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, employee.getName());
            ps.setString(2, employee.getGender());
            ps.setDate(3, new java.sql.Date(employee.getBirthday().getTime()));
            ps.setString(4, employee.getPosition());
            ps.setString(5, employee.getPhone());

            int result = ps.executeUpdate();
            if (result > 0) {
                ResultSet rs = ps.getGeneratedKeys();
                if (rs.next()) {
                    employee.setId(rs.getInt(1));
                }
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, null);
        }

        return false;
    }

    @Override
    public boolean update(Employee employee) {
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE employee SET name=?, gender=?, birthday=?, position=?, phone=? WHERE id=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, employee.getName());
            ps.setString(2, employee.getGender());
            ps.setDate(3, new java.sql.Date(employee.getBirthday().getTime()));
            ps.setString(4, employee.getPosition());
            ps.setString(5, employee.getPhone());
            ps.setInt(6, employee.getId());

            return ps.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, null);
        }

        return false;
    }

    @Override
    public boolean delete(Integer id) {
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "DELETE FROM employee WHERE id=?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, id);

            return ps.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, null);
        }

        return false;
    }
}

// CropDAOImpl.java
class CropDAOImpl implements BaseDAO<Crop> {
    @Override
    public List<Crop> findAll() {
        List<Crop> crops = new ArrayList<>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM crop";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();

            while (rs.next()) {
                Crop crop = DBUtil.resultSetToEntity(rs, Crop.class);
                crops.add(crop);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, rs);
        }

        return crops;
    }

    @Override
    public Crop findById(Integer id) {
        // 实现根据ID查询...
        return null;
    }

    @Override
    public boolean save(Crop crop) {
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO crop(name, type, growth_cycle, price) VALUES (?, ?, ?, ?)";
            ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            ps.setString(1, crop.getName());
            ps.setString(2, crop.getType());
            ps.setInt(3, crop.getGrowthCycle());
            ps.setDouble(4, crop.getPrice());

            int result = ps.executeUpdate();
            if (result > 0) {
                ResultSet rs = ps.getGeneratedKeys();
                if (rs.next()) {
                    crop.setId(rs.getInt(1));
                }
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, null);
        }

        return false;
    }

    @Override
    public boolean update(Crop crop) {
        // 实现更新...
        return false;
    }

    @Override
    public boolean delete(Integer id) {
        // 实现删除...
        return false;
    }
}

// LandDAOImpl.java
class LandDAOImpl implements BaseDAO<Land> {
    @Override
    public List<Land> findAll() {
        List<Land> lands = new ArrayList<>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM land";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();

            while (rs.next()) {
                Land land = DBUtil.resultSetToEntity(rs, Land.class);
                lands.add(land);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, rs);
        }

        return lands;
    }

    @Override
    public Land findById(Integer id) {
        // 实现根据ID查询...
        return null;
    }

    @Override
    public boolean save(Land land) {
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO land(area, soil_type, status) VALUES (?, ?, ?)";
            ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            ps.setDouble(1, land.getArea());
            ps.setString(2, land.getSoilType());
            ps.setString(3, land.getStatus());

            int result = ps.executeUpdate();
            if (result > 0) {
                ResultSet rs = ps.getGeneratedKeys();
                if (rs.next()) {
                    land.setId(rs.getInt(1));
                }
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, null);
        }

        return false;
    }

    @Override
    public boolean update(Land land) {
        // 实现更新...
        return false;
    }

    @Override
    public boolean delete(Integer id) {
        // 实现删除...
        return false;
    }
}

// PlantingPlanDAOImpl.java
class PlantingPlanDAOImpl implements BaseDAO<PlantingPlan> {
    @Override
    public List<PlantingPlan> findAll() {
        List<PlantingPlan> plans = new ArrayList<>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM planting_plan";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();

            while (rs.next()) {
                PlantingPlan plan = DBUtil.resultSetToEntity(rs, PlantingPlan.class);
                plans.add(plan);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, rs);
        }

        return plans;
    }

    @Override
    public PlantingPlan findById(Integer id) {
        // 实现根据ID查询...
        return null;
    }

    @Override
    public boolean save(PlantingPlan plan) {
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO planting_plan(crop_id, land_id, employee_id, plan_date, estimated_harvest_date, actual_harvest_date, status) VALUES (?, ?, ?, ?, ?, ?, ?)";
            ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            ps.setInt(1, plan.getCropId());
            ps.setInt(2, plan.getLandId());
            ps.setInt(3, plan.getEmployeeId());
            ps.setDate(4, new java.sql.Date(plan.getPlanDate().getTime()));
            ps.setDate(5, new java.sql.Date(plan.getEstimatedHarvestDate().getTime()));
            ps.setDate(6, plan.getActualHarvestDate() != null ? new java.sql.Date(plan.getActualHarvestDate().getTime()) : null);
            ps.setString(7, plan.getStatus());

            int result = ps.executeUpdate();
            if (result > 0) {
                ResultSet rs = ps.getGeneratedKeys();
                if (rs.next()) {
                    plan.setId(rs.getInt(1));
                }
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, null);
        }

        return false;
    }

    @Override
    public boolean update(PlantingPlan plan) {
        // 实现更新...
        return false;
    }

    @Override
    public boolean delete(Integer id) {
        // 实现删除...
        return false;
    }
}

// FarmService.java - 使用集合
class FarmService {
    private EmployeeDAOImpl employeeDAO = new EmployeeDAOImpl();
    private CropDAOImpl cropDAO = new CropDAOImpl();
    private LandDAOImpl landDAO = new LandDAOImpl();
    private PlantingPlanDAOImpl plantingPlanDAO = new PlantingPlanDAOImpl();

    // 员工管理
    public List<Employee> getAllEmployees() {
        return employeeDAO.findAll();
    }

    public boolean addEmployee(Employee employee) {
        return employeeDAO.save(employee);
    }

    public boolean updateEmployee(Employee employee) {
        return employeeDAO.update(employee);
    }

    public boolean deleteEmployee(Integer id) {
        return employeeDAO.delete(id);
    }

    // 农作物管理
    public List<Crop> getAllCrops() {
        return cropDAO.findAll();
    }

    public boolean addCrop(Crop crop) {
        return cropDAO.save(crop);
    }

    // 土地管理
    public List<Land> getAllLands() {
        return landDAO.findAll();
    }

    public boolean addLand(Land land) {
        return landDAO.save(land);
    }

    // 种植计划管理
    public List<PlantingPlan> getAllPlans() {
        return plantingPlanDAO.findAll();
    }

    public boolean addPlan(PlantingPlan plan) {
        return plantingPlanDAO.save(plan);
    }

    // 其他业务方法...
}

// MathUtil.java - 使用Math类
class MathUtil {
    // 计算土地面积对应的产量（模拟计算）
    public static double calculateYield(double area, double fertility) {
        // 使用Math.random模拟产量波动
        double randomFactor = 0.8 + (Math.random() * 0.4); // 0.8-1.2的随机因子
        return area * fertility * randomFactor;
    }

    // 计算产值
    public static double calculateValue(double yield, double price) {
        return yield * price;
    }
}

// FarmConsoleUI.java - CMD模式菜单
public class FarmConsoleUI {
    private static FarmService farmService = new FarmService();
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        showMainMenu();
    }

    private static void showMainMenu() {
        while (true) {
            System.out.println("\n===== 农场管理系统 =====");
            System.out.println("1. 员工管理");
            System.out.println("2. 农作物管理");
            System.out.println("3. 土地管理");
            System.out.println("4. 种植计划管理");
            System.out.println("5. 退出系统");
            System.out.print("请选择操作: ");

            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符

            switch (choice) {
                case 1:
                    showEmployeeMenu();
                    break;
                case 2:
                    showCropMenu();
                    break;
                case 3:
                    showLandMenu();
                    break;
                case 4:
                    showPlantingPlanMenu();
                    break;
                case 5:
                    System.out.println("感谢使用农场管理系统，再见！");
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private static void showEmployeeMenu() {
        while (true) {
            System.out.println("\n===== 员工管理 =====");
            System.out.println("1. 查看所有员工");
            System.out.println("2. 添加员工");
            System.out.println("3. 修改员工信息");
            System.out.println("4. 删除员工");
            System.out.println("5. 返回主菜单");
            System.out.print("请选择操作: ");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    listEmployees();
                    break;
                case 2:
                    addEmployee();
                    break;
                case 3:
                    updateEmployee();
                    break;
                case 4:
                    deleteEmployee();
                    break;
                case 5:
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private static void listEmployees() {
        System.out.println("\n----- 员工列表 -----");
        List<Employee> employees = farmService.getAllEmployees();

        if (employees.isEmpty()) {
            System.out.println("没有员工记录");
            return;
        }

        // 使用String.format格式化输出
        System.out.println(String.format("%-4s %-10s %-4s %-12s %-10s %-11s",
                "ID", "姓名", "性别", "生日", "职位", "电话"));

        for (Employee emp : employees) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String birthdayStr = sdf.format(emp.getBirthday());

            System.out.println(String.format("%-4d %-10s %-4s %-12s %-10s %-11s",
                    emp.getId(), emp.getName(), emp.getGender(),
                    birthdayStr, emp.getPosition(), emp.getPhone()));
        }
    }

    private static void addEmployee() {
        System.out.println("\n----- 添加员工 -----");

        Employee employee = new Employee();

        System.out.print("请输入姓名: ");
        employee.setName(scanner.nextLine());

        System.out.print("请输入性别(男/女): ");
        employee.setGender(scanner.nextLine());

        System.out.print("请输入生日(YYYY-MM-DD): ");
        String birthdayStr = scanner.nextLine();
        // 使用SimpleDateFormat解析日期
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date birthday = sdf.parse(birthdayStr);
            employee.setBirthday(birthday);
        } catch (ParseException e) {
            System.out.println("日期格式错误，使用当前日期");
            employee.setBirthday(new Date());
        }

        System.out.print("请输入职位: ");
        employee.setPosition(scanner.nextLine());

        System.out.print("请输入电话: ");
        employee.setPhone(scanner.nextLine());

        if (farmService.addEmployee(employee)) {
            System.out.println("员工添加成功！");
        } else {
            System.out.println("员工添加失败！");
        }
    }

    private static void updateEmployee() {
        System.out.println("\n----- 修改员工信息 -----");
        System.out.print("请输入要修改的员工ID: ");
        int id = scanner.nextInt();
        scanner.nextLine(); // 消耗换行符

        Employee employee = farmService.getAllEmployees().stream()
                .filter(e -> e.getId() == id)
                .findFirst()
                .orElse(null);

        if (employee == null) {
            System.out.println("未找到该员工！");
            return;
        }

        System.out.println("当前员工信息:");
        System.out.println("姓名: " + employee.getName());
        System.out.println("性别: " + employee.getGender());
        System.out.println("生日: " + new SimpleDateFormat("yyyy-MM-dd").format(employee.getBirthday()));
        System.out.println("职位: " + employee.getPosition());
        System.out.println("电话: " + employee.getPhone());

        System.out.print("请输入新姓名(直接回车不修改): ");
        String name = scanner.nextLine();
        if (!name.isEmpty()) {
            employee.setName(name);
        }

        System.out.print("请输入新性别(直接回车不修改): ");
        String gender = scanner.nextLine();
        if (!gender.isEmpty()) {
            employee.setGender(gender);
        }

        System.out.print("请输入新生日(YYYY-MM-DD，直接回车不修改): ");
        String birthdayStr = scanner.nextLine();
        if (!birthdayStr.isEmpty()) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date birthday = sdf.parse(birthdayStr);
                employee.setBirthday(birthday);
            } catch (ParseException e) {
                System.out.println("日期格式错误，保持原日期");
            }
        }

        System.out.print("请输入新职位(直接回车不修改): ");
        String position = scanner.nextLine();
        if (!position.isEmpty()) {
            employee.setPosition(position);
        }

        System.out.print("请输入新电话(直接回车不修改): ");
        String phone = scanner.nextLine();
        if (!phone.isEmpty()) {
            employee.setPhone(phone);
        }

        if (farmService.updateEmployee(employee)) {
            System.out.println("员工信息修改成功！");
        } else {
            System.out.println("员工信息修改失败！");
        }
    }

    private static void deleteEmployee() {
        System.out.println("\n----- 删除员工 -----");
        System.out.print("请输入要删除的员工ID: ");
        int id = scanner.nextInt();
        scanner.nextLine(); // 消耗换行符

        System.out.print("确定要删除该员工吗？(y/n): ");
        String confirm = scanner.nextLine();

        if (confirm.equalsIgnoreCase("y")) {
            if (farmService.deleteEmployee(id)) {
                System.out.println("员工删除成功！");
            } else {
                System.out.println("员工删除失败！");
            }
        } else {
            System.out.println("已取消删除操作");
        }
    }

    private static void showCropMenu() {
        while (true) {
            System.out.println("\n===== 农作物管理 =====");
            System.out.println("1. 查看所有农作物");
            System.out.println("2. 添加农作物");
            System.out.println("3. 返回主菜单");
            System.out.print("请选择操作: ");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    listCrops();
                    break;
                case 2:
                    addCrop();
                    break;
                case 3:
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private static void listCrops() {
        System.out.println("\n----- 农作物列表 -----");
        List<Crop> crops = farmService.getAllCrops();

        if (crops.isEmpty()) {
            System.out.println("没有农作物记录");
            return;
        }

        System.out.println(String.format("%-4s %-10s %-10s %-12s %-8s",
                "ID", "名称", "类型", "生长周期(天)", "价格"));

        for (Crop crop : crops) {
            System.out.println(String.format("%-4d %-10s %-10s %-12d %-8.2f",
                    crop.getId(), crop.getName(), crop.getType(),
                    crop.getGrowthCycle(), crop.getPrice()));
        }
    }

    private static void addCrop() {
        System.out.println("\n----- 添加农作物 -----");

        Crop crop = new Crop();

        System.out.print("请输入名称: ");
        crop.setName(scanner.nextLine());

        System.out.print("请输入类型: ");
        crop.setType(scanner.nextLine());

        System.out.print("请输入生长周期(天): ");
        crop.setGrowthCycle(scanner.nextInt());
        scanner.nextLine(); // 消耗换行符

        System.out.print("请输入价格: ");
        crop.setPrice(scanner.nextDouble());
        scanner.nextLine(); // 消耗换行符

        if (farmService.addCrop(crop)) {
            System.out.println("农作物添加成功！");
        } else {
            System.out.println("农作物添加失败！");
        }
    }

    private static void showLandMenu() {
        while (true) {
            System.out.println("\n===== 土地管理 =====");
            System.out.println("1. 查看所有土地");
            System.out.println("2. 添加土地");
            System.out.println("3. 返回主菜单");
            System.out.print("请选择操作: ");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    listLands();
                    break;
                case 2:
                    addLand();
                    break;
                case 3:
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private static void listLands() {
        System.out.println("\n----- 土地列表 -----");
        List<Land> lands = farmService.getAllLands();

        if (lands.isEmpty()) {
            System.out.println("没有土地记录");
            return;
        }

        System.out.println(String.format("%-4s %-8s %-10s %-8s",
                "ID", "面积(亩)", "土壤类型", "状态"));

        for (Land land : lands) {
            System.out.println(String.format("%-4d %-8.2f %-10s %-8s",
                    land.getId(), land.getArea(), land.getSoilType(), land.getStatus()));
        }
    }

    private static void addLand() {
        System.out.println("\n----- 添加土地 -----");

        Land land = new Land();

        System.out.print("请输入面积(亩): ");
        land.setArea(scanner.nextDouble());
        scanner.nextLine(); // 消耗换行符

        System.out.print("请输入土壤类型: ");
        land.setSoilType(scanner.nextLine());

        System.out.print("请输入状态: ");
        land.setStatus(scanner.nextLine());

        if (farmService.addLand(land)) {
            System.out.println("土地添加成功！");
        } else {
            System.out.println("土地添加失败！");
        }
    }

    private static void showPlantingPlanMenu() {
        while (true) {
            System.out.println("\n===== 种植计划管理 =====");
            System.out.println("1. 查看所有种植计划");
            System.out.println("2. 添加种植计划");
            System.out.println("3. 返回主菜单");
            System.out.print("请选择操作: ");

            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    listPlans();
                    break;
                case 2:
                    addPlan();
                    break;
                case 3:
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    private static void addPlan() {
        System.out.println("\n----- 添加种植计划 -----");

        PlantingPlan plan = new PlantingPlan();

        System.out.print("请输入作物ID: ");
        plan.setCropId(scanner.nextInt());
        scanner.nextLine(); // 消耗换行符

        System.out.print("请输入土地ID: ");
        plan.setLandId(scanner.nextInt());
        scanner.nextLine(); // 消耗换行符

        System.out.print("请输入员工ID: ");
        plan.setEmployeeId(scanner.nextInt());
        scanner.nextLine(); // 消耗换行符

        System.out.print("请输入计划日期(YYYY-MM-DD): ");
        String planDateStr = scanner.nextLine();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date planDate = sdf.parse(planDateStr);
            plan.setPlanDate(planDate);
        } catch (ParseException e) {
            System.out.println("日期格式错误，使用当前日期");
            plan.setPlanDate(new Date());
        }

        System.out.print("请输入预计收获日期(YYYY-MM-DD): ");
        String estimatedHarvestDateStr = scanner.nextLine();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date estimatedHarvestDate = sdf.parse(estimatedHarvestDateStr);
            plan.setEstimatedHarvestDate(estimatedHarvestDate);
        } catch (ParseException e) {
            System.out.println("日期格式错误，设置为空");
            plan.setEstimatedHarvestDate(null);
        }

        System.out.print("请输入状态: ");
        plan.setStatus(scanner.nextLine());

        if (farmService.addPlan(plan)) {
            System.out.println("种植计划添加成功！");
        } else {
            System.out.println("种植计划添加失败！");
        }
    }

    private static void listPlans() {
        System.out.println("\n----- 种植计划列表 -----");
        List<PlantingPlan> plans = farmService.getAllPlans();

        if (plans.isEmpty()) {
            System.out.println("没有种植计划记录");
            return;
        }

        // 修复格式字符串和参数数量不匹配的问题
        System.out.println(String.format("%-4s %-8s %-8s %-8s %-12s %-18s %-18s %-8s",
                "ID", "作物ID", "土地ID", "员工ID", "计划日期", "预计收获日期", "实际收获日期", "状态"));

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (PlantingPlan plan : plans) {
            String planDateStr = plan.getPlanDate() != null ? sdf.format(plan.getPlanDate()) : "N/A";
            String estimatedHarvestDateStr = plan.getEstimatedHarvestDate() != null ? sdf.format(plan.getEstimatedHarvestDate()) : "N/A";
            String actualHarvestDateStr = plan.getActualHarvestDate() != null ? sdf.format(plan.getActualHarvestDate()) : "N/A";

            System.out.println(String.format("%-4d %-8d %-8d %-8d %-12s %-18s %-18s %-8s",
                    plan.getId(),
                    plan.getCropId(),
                    plan.getLandId(),
                    plan.getEmployeeId(),
                    planDateStr,
                    estimatedHarvestDateStr,
                    actualHarvestDateStr,
                    plan.getStatus()));
        }
    }
}